using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using Lib.Approval;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2.ApplicationStateServices;
using MSIACCSL2.Command;
using MSIACCSL2.InventoryServices;
using MSIACCSL2.PurchaseInvoiceServices;
using MSIACCSL2.PurchaseReturnServices;
using MSIACCSL2.SupplierServices;
using MSIACCSL2.Views.PurchaseReturn;
using MSIACCSL2.WarehouseServices;
using WcfService1.DTO;
using DeleteDetailCompletedEventArgs = MSIACCSL2.PurchaseReturnServices.DeleteDetailCompletedEventArgs;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.PurchaseReturnServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.PurchaseReturnServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.PurchaseReturnServices.SaveCompletedEventArgs;


namespace MSIACCSL2.ViewModels
{
    public class PurchaseReturnViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static Search frmSearch;
        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        public static Completed OnSearchCompleted;
        private static NavigationService _NavigationService;
        private readonly AplicationStateServicesClient ApplicationService;
        private readonly InventoryServiceClient InventoryClient;
        private readonly PurchaseInvoiceServicesClient PurchaseInvoiceClient;
        private readonly SupplierServicesClient SupplierClient;


        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private bool IsUsed;
        private ObservableCollection<int> Pages;
        private bool _IsBusy;
        private bool _IsEnabled;
        private ObservableCollection<PurchaseInvoiceDTO> _PurchaseInvoices;
        private PurchaseReturnDTO _PurchaseReturn;
        private PagedCollectionView _PurchaseReturns;
        private Visibility _SupplierVisibility;
        private ObservableCollection<SupplierDTO> _Suppliers;
        private List<string> _errors;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private PurchaseReturnServicesClient client;
        private Dictionary<string, object> criteria;
        private string expression;
        private readonly WarehouseServicesClient WarehouseClient;
        private ObservableCollection<WarehouseDTO> _warehouses;

        public PurchaseReturnViewModel()
        {
            SupplierVisibility = Visibility.Collapsed;
            IsEnabled = true;

            if (!DesignerProperties.IsInDesignTool)
            {
                client = new PurchaseReturnServicesClient();
                PurchaseInvoiceClient = new PurchaseInvoiceServicesClient();
                SupplierClient = new SupplierServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SavePurchaseReturn, CanSave);
                New = new DelegateCommand(NewPurchaseReturn, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchPurchaseReturn, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                LoadPICommand = new DelegateCommand(LoadPI, CanLoadPICommand);
                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                Errors = new List<string>();
                InventoryClient = new InventoryServiceClient();
                ApplicationService = new AplicationStateServicesClient();
                WarehouseClient = new WarehouseServicesClient();

                if (mode == Mode.Edit)
                {
                    PurchaseReturn = (PurchaseReturnDTO) Navigation.Args;
                    if (PurchaseReturn.PurchaseReturnDetails == null)
                        PurchaseReturn.PurchaseReturnDetails = new ObservableCollection<PurchaseReturnDetailDTO>();
                    if (PurchaseReturn.PurchaseReturnDetails.Count == 0)
                        PurchaseReturn.PurchaseReturnDetails.Add(new PurchaseReturnDetailDTO());
                    GetPurchaseInvoiceList();
                    GetSupplierList();
                    CekTransaksi();
                    GetWarehouseList();
                }
                else if (mode == Mode.Search)
                {
                    PurchaseReturn = new PurchaseReturnDTO();
                    PurchaseReturn.PRDate = null;
                    GetPurchaseInvoiceList();
                    GetSupplierList();
                }
                else if (mode == Mode.Add)
                {
                    //GetLastNoPurchaseReturn();
                    GetPurchaseInvoiceList();
                    GetSupplierList();
                    GetWarehouseList();

                    PurchaseReturn = new PurchaseReturnDTO();
                    PurchaseReturn.PurchaseReturnDetails = new ObservableCollection<PurchaseReturnDetailDTO>();
                    var PurchaseReturnDetail = new PurchaseReturnDetailDTO();
                    PurchaseReturnDetail.Inventory = new InventoryDTO();
                    PurchaseReturn.PurchaseReturnDetails.Add(PurchaseReturnDetail);
                    //CekTransaksi();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }

        public PagedCollectionView PurchaseReturns
        {
            get { return _PurchaseReturns; }

            private set
            {
                if (PurchaseReturns == value) return;
                _PurchaseReturns = value;
                int i = (CurrentPage*30);
                foreach (object PurchaseReturn in PurchaseReturns)
                {
                    i += 1;

                    ((PurchaseReturnDTO) PurchaseReturn).No = i;
                }
                FirePropertyChanged("PurchaseReturns");
                PurchaseReturns.CollectionChanged += PurchaseReturn_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<PurchaseInvoiceDTO> PurchaseInvoices
        {
            get { return _PurchaseInvoices; }
            private set
            {
                if (PurchaseInvoices == value) return;
                _PurchaseInvoices = value;
                FirePropertyChanged("PurchaseInvoices");
            }
        }


        public ObservableCollection<SupplierDTO> Suppliers
        {
            get { return _Suppliers; }
            private set
            {
                if (Suppliers == value) return;
                _Suppliers = value;
                FirePropertyChanged("Suppliers");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }


        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public PurchaseReturnDTO PurchaseReturn
        {
            get { return _PurchaseReturn; }
            private set
            {
                if (PurchaseReturn == value) return;
                _PurchaseReturn = value;
                FirePropertyChanged("PurchaseReturn");
            }
        }

        public Visibility SupplierVisibility
        {
            get { return _SupplierVisibility; }
            internal set
            {
                _SupplierVisibility = value;
                FirePropertyChanged("SupplierVisibility");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }

        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _warehouses; }
            private set
            {
                if (Warehouses == value) return;
                _warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }

        public ICommand LoadPICommand { get; set; }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void PurchaseReturn_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SavePurchaseReturn(Object purchaseReturn)
        {
            if (PurchaseReturn.PurchaseReturnDetails.Count == 1)
            {
                //Bila tidak ada yang dipilih di detail maka details harus dihapus
                if (PurchaseReturn.PurchaseReturnDetails[0].Inventory == null)
                    PurchaseReturn.PurchaseReturnDetails.Clear();
            }
            Validate();
            if (Errors.Count > 0) return;
            PurchaseReturn.created_by = GlobalVar.User.UserID;
            PurchaseReturn.modified_by = GlobalVar.User.UserID;
            IsBusy = true;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync(PurchaseReturn, mode);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            if (e.Error != null) Validate(e.Error.ToString());
            client.SaveCompleted -= client_SaveCompleted;
            mode = (Mode) e.UserState;
            if (e.Result)
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/PurchaseReturn/Index", UriKind.Relative));
            }
            else
            {
                IsBusy = false;
                if (e.Error != null)
                    MessageBox.Show(e.Error.Message);
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            PurchaseReturns = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewPurchaseReturn(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/PurchaseReturn/frmAdd", UriKind.Relative));
        }


        private void SearchPurchaseReturn(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in PurchaseReturn.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(PurchaseReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(PurchaseReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(PurchaseReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(PurchaseReturn, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(PurchaseReturn, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(PurchaseReturn, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(PurchaseReturn, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(PurchaseReturn, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(PurchaseReturn, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(PurchaseReturn, null));
                }
            }

            expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            PurchaseReturnSearch(criteria, expression,1);
        }

        private void PurchaseReturnSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, page);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            PurchaseReturns = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
        }


        private void GetPurchaseInvoiceList()
        {
            PurchaseInvoiceClient.GetAllPurchaseInvoiceCompleted += PurchaseInvoiceClient_GetAllPurchaseInvoiceCompleted;
            PurchaseInvoiceClient.GetAllPurchaseInvoiceAsync();
        }

        private void PurchaseInvoiceClient_GetAllPurchaseInvoiceCompleted(object sender,
                                                                          GetAllPurchaseInvoiceCompletedEventArgs e)
        {
            PurchaseInvoiceClient.GetAllPurchaseInvoiceCompleted -= PurchaseInvoiceClient_GetAllPurchaseInvoiceCompleted;
            PurchaseInvoices = e.Result;

            if (PurchaseReturn != null)
            {
                if (PurchaseReturn.PurchaseInvoice == null) return;
                PurchaseReturn.PurchaseInvoice =
                    PurchaseInvoices.FirstOrDefault(
                        s => s.PINo == PurchaseReturn.PurchaseInvoice.PINo);
            }
        }

        private void GetSupplierList()
        {
            SupplierClient.GetAllSupplierCompleted += SupplierClient_GetAllSupplierCompleted;
            SupplierClient.GetAllSupplierAsync();
        }

        private void SupplierClient_GetAllSupplierCompleted(object sender, GetAllSupplierCompletedEventArgs e)
        {
            SupplierClient.GetAllSupplierCompleted -= SupplierClient_GetAllSupplierCompleted;
            Suppliers = e.Result;

            if (PurchaseReturn != null)
            {
                if (PurchaseReturn.Supplier == null) return;
                PurchaseReturn.Supplier =
                    Suppliers.FirstOrDefault(s => s.SupplierId == PurchaseReturn.Supplier.SupplierId);
            }
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            PurchaseReturn = null;
            if (PurchaseReturns != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (mode == Mode.Search)
                    PurchaseReturnSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            PurchaseReturn = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (PurchaseReturns == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors.Clear();
            //if (string.IsNullOrEmpty(PurchaseReturn.PRNo))
            //    Errors.Add("Nomor PR tidak boleh kosong");
            if (PurchaseReturn.PurchaseInvoice == null)
                Errors.Add("PI Belum dipilih !");

            if (PurchaseReturn.Warehouse == null)
                    Errors.Add("Warehouse harus dipilih!");

            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
            {
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                MessageVisibility = Visibility.Collapsed;
            }
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (!IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }

        private void GetLastNoPurchaseReturn()
        {
            client = new PurchaseReturnServicesClient();
            client.GetLastPRNoCompleted += client_GetLastPRNoCompleted;
            client.GetLastPRNoAsync();
        }

        private void client_GetLastPRNoCompleted(object sender, GetLastPRNoCompletedEventArgs e)
        {
            client.GetLastPRNoCompleted -= client_GetLastPRNoCompleted;
            string res = e.Result;
            string formatSO = "0000";
            string kodeSO;
            if (e.Result.Length <= 4)
            {
                res = formatSO;
                kodeSO = e.Result;
            }
            else
            {
                res = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[2];
                kodeSO = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[0];
            }
            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(res) + 1).ToString().Length) +
                           (int.Parse(res) + 1);

            PurchaseReturn.PRNo = kodeSO + "/" + DateTime.Now.Year + "/" + soNum;
        }

        public bool CanLoadPICommand(Object param)
        {
            return true;
        }

        public void LoadPI(Object param)
        {
            if (param == null) return;
            var pi = (PurchaseInvoiceDTO) param;
            PurchaseInvoiceClient.GetPurchaseInvoiceCompleted += PurchaseInvoiceClient_GetPurchaseInvoiceCompleted;
            PurchaseInvoiceClient.GetPurchaseInvoiceAsync(pi.PINo);
        }

        private void PurchaseInvoiceClient_GetPurchaseInvoiceCompleted(object sender,
                                                                       GetPurchaseInvoiceCompletedEventArgs e)
        {
            if (PurchaseReturn == null) return;
            foreach (SupplierDTO supplier in Suppliers.Where(c => c.SupplierId == e.Result.Supplier.SupplierId))
                PurchaseReturn.Supplier = supplier;
            PurchaseReturn.PurchaseReturnDetails.Clear();

            foreach (PurchaseInvoiceDetailDTO pid in e.Result.PurchaseInvoiceDetails)
            {
                var prd = new PurchaseReturnDetailDTO();
                prd.Inventory = pid.Inventory;
                prd.Panjang = pid.Inventory.Panjang;
                prd.Lebar = pid.Inventory.Lebar;
                prd.Qty = pid.Inventory.QtyUnit;
                prd.Inventory.Item =
                    pid.Inventory.Item;
                prd.Price = pid.Price;
                prd.Discount = pid.Discount;
                PurchaseReturn.PurchaseReturnDetails.Add(prd);
            }
        }

        public void GetSupplier(Object param)
        {
            SupplierClient.GetSupplierListCompleted += SupplierClient_GetSupplierListCompleted;
            SupplierClient.GetSupplierListAsync(param.ToString());
        }

        private void SupplierClient_GetSupplierListCompleted(object sender, GetSupplierListCompletedEventArgs e)
        {
            SupplierClient.GetSupplierListCompleted -= SupplierClient_GetSupplierListCompleted;
            Suppliers = e.Result;
            SupplierVisibility = Visibility.Visible;
            EventAggregator.PublishMessage("SupplierSelect", string.Empty);
        }

        public void SupplierSelected(Object param)
        {
            PurchaseReturn.Supplier = ((SupplierDTO) param);
            SupplierVisibility = Visibility.Collapsed;
        }

        public void Print(Object param)
        {
            Navigation.MyNavigation.Navigate(new Uri("/PurchaseReturn/PrintPreviewPR", UriKind.Relative));
            Navigation.Args = param;
        }

        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as PurchaseReturnDTO, (x as WarehouseDTO).EmailFolder);
            });

        }

        private void client_SendEmailCompleted(object sender, SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }

        public void GetQtyOnHand(Object param)
        {
            var prDetail = param as PurchaseReturnDetailDTO;
            InventoryClient.GetQtyOnHandCompleted += InventoryClient_GetQtyOnHandCompleted;
            InventoryClient.GetQtyOnHandAsync(prDetail.Inventory.SerialNumber,PurchaseReturn.Warehouse.KodeWarehouse,
                                              prDetail);
        }

        private void InventoryClient_GetQtyOnHandCompleted(object sender, GetQtyOnHandCompletedEventArgs e)
        {
            InventoryClient.GetQtyOnHandCompleted -= InventoryClient_GetQtyOnHandCompleted;
            var prDetail = e.UserState as PurchaseReturnDetailDTO;
            prDetail.Qty = e.Result.Qty;
            prDetail.Inventory.Tinggi = e.Result.Sheet;
            if (prDetail.Qty == 0)
                MessageBox.Show("Pilih Gudang yang lain, tidak ada Stok di Gudang ini!");
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(PurchaseReturn.PRNo))
            {
                ApplicationService.IsTransactionUsedAsync(PurchaseReturn.ToString(), GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = PurchaseReturn.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(PurchaseReturn.PRNo, GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = PurchaseReturn.PRNo;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/PurchaseReturn/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(PurchaseReturn.ToString(), GlobalVar.User);
            else
                ApplicationService.ClearTransactionAsync(PurchaseReturn.PRNo, GlobalVar.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }
        public void GetWarehouseList()
        {
            WarehouseClient.GetAllWarehouseCompleted += WarehouseClient_GetAllWarehouseCompleted;
            WarehouseClient.GetAllWarehouseAsync();
        }

        private void WarehouseClient_GetAllWarehouseCompleted(object sender, GetAllWarehouseCompletedEventArgs e)
        {
            WarehouseClient.GetAllWarehouseCompleted -= WarehouseClient_GetAllWarehouseCompleted;
            Warehouses = e.Result;
            if (PurchaseReturn != null)
                if (PurchaseReturn.Warehouse != null)
                    PurchaseReturn.Warehouse =
                                    Warehouses.FirstOrDefault(
                                        x => x.KodeWarehouse == PurchaseReturn.Warehouse.KodeWarehouse);
        }

        public void CloseStatus()
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Close this Transaction ?", "Confirmation",
                                                MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                client.UpdateStatusCompleted += new EventHandler<AsyncCompletedEventArgs>(client_UpdateStatusCompleted);
                client.UpdateStatusAsync(PurchaseReturn, Status.Close);
            }
        }

        void client_UpdateStatusCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.UpdateStatusCompleted -= new EventHandler<AsyncCompletedEventArgs>(client_UpdateStatusCompleted);
            MessageBox.Show("Update Status finished!");
        }

    }


    public class PurchaseReturnWrapViewModel : ViewModelBase
    {
        private readonly InventoryServiceClient Inventoryclient;
        private readonly WarehouseServicesClient WarehouseClient;
        private readonly PurchaseReturnServicesClient client;

        private ObservableCollection<InventoryDTO> _Inventorys;
        private PurchaseReturnDetailDTO _PurchaseReturnDetail;
        private ObservableCollection<WarehouseDTO> _warehouses;


        public PurchaseReturnWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new PurchaseReturnServicesClient();
                Inventoryclient = new InventoryServiceClient();
                WarehouseClient = new WarehouseServicesClient();
                GetInventoryCommand = new DelegateCommand(GetInventory, CanGetInventoryCommand);
                GetQtyUnitCommand = new DelegateCommand(GetQtyUnit, CanGetQtyUnit);

                AddDetailCommand = new DelegateCommand(AddPurchaseReturnDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeletePurchaseReturnDetail, CanDeleteDetailCommand);
                if (PurchaseReturnViewModel.mode == Mode.Add || PurchaseReturnViewModel.mode == Mode.Edit)
                {
                    
                }
            }
        }

        public PurchaseReturnViewModel PurchaseReturnViewModel { get; set; }


        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }


        public ObservableCollection<InventoryDTO> Inventorys
        {
            get { return _Inventorys; }
            private set
            {
                if (Inventorys == value) return;
                _Inventorys = value;
                FirePropertyChanged("Inventorys");
            }
        }


        public PurchaseReturnDetailDTO PurchaseReturnDetail
        {
            get { return _PurchaseReturnDetail; }
            private set
            {
                if (PurchaseReturnDetail == value) return;
                _PurchaseReturnDetail = value;
                FirePropertyChanged("PurchaseReturnDetail");
            }
        }
      

        public ICommand GetInventoryCommand { get; set; }
        public ICommand GetQtyUnitCommand { get; set; }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            PurchaseReturnViewModel.mode = Mode.Edit;
            Navigation.MyNavigation.Navigate(new Uri("/PurchaseReturn/frmAdd", UriKind.Relative));
            Navigation.Args = param;
        }

        public void Delete(Object param)
        {
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((PurchaseReturnDTO)param);
            });

        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            PurchaseReturnViewModel.mode = Mode.Idle;
            var VM = new PurchaseReturnViewModel();
        }


        public void GetInventoryList()
        {
            Inventoryclient.GetInventoryByCriteriaCompleted += Inventoryclient_GetInventoryByCriteriaCompleted;
            Inventoryclient.GetInventoryByCriteriaAsync(new Dictionary<string, object>(), null, 1);
        }

        private void Inventoryclient_GetInventoryByCriteriaCompleted(object sender,
                                                                     GetInventoryByCriteriaCompletedEventArgs e)
        {
            Inventorys = e.Result;
            if (PurchaseReturnViewModel.PurchaseReturn != null)
            {
                foreach (
                    PurchaseReturnDetailDTO PurchaseReturnDetail in
                        PurchaseReturnViewModel.PurchaseReturn.PurchaseReturnDetails)
                {
                    if (PurchaseReturnDetail.Inventory == null) continue;
                    PurchaseReturnDetail.Inventory =
                        Inventorys.FirstOrDefault(s => s.SerialNumber == PurchaseReturnDetail.Inventory.SerialNumber);
                }
            }
        }


        public void GetInventory(Object param)
        {
            PurchaseReturnDetail = (PurchaseReturnDetailDTO) param;
            if (PurchaseReturnDetail.Inventory == null) PurchaseReturnDetail.Inventory = new InventoryDTO();
            string SerialNumber = PurchaseReturnDetail.Inventory.SerialNumber;
            Inventoryclient.GetInventoryCompleted +=
                InventoryClient_GetInventoryCompleted;
            Inventoryclient.GetInventoryAsync(SerialNumber);
        }

        private void InventoryClient_GetInventoryCompleted(object sender, GetInventoryCompletedEventArgs e)
        {
            //validasi

            Inventoryclient.GetInventoryCompleted -=
                InventoryClient_GetInventoryCompleted;
            InventoryDTO InventoryTemp = e.Result;
            if (null != InventoryTemp && ! string.IsNullOrEmpty(InventoryTemp.SerialNumber))
            {
                PurchaseReturnDetail.Inventory = InventoryTemp;
                PurchaseReturnDetail.Inventory.Item =
                    e.Result.Item;
                PurchaseReturnDetail.Inventory.SatuanUnit =
                    e.Result.SatuanUnit;
                PurchaseReturnDetail.Panjang = InventoryTemp.Panjang;
                PurchaseReturnDetail.Lebar = InventoryTemp.Lebar;
                PurchaseReturnDetail.Tinggi = InventoryTemp.Warehouses.FirstOrDefault().Sheet;
                PurchaseReturnDetail.Qty = InventoryTemp.Warehouses.FirstOrDefault().Qty;
            }else
            {
                MessageBox.Show("Barang tidak ditemukan, coba entry secara manual");
            }
        }

        public void AddPurchaseReturnDetail(Object param)
        {
            PurchaseReturnDetail = new PurchaseReturnDetailDTO();
            PurchaseReturnDetail.Inventory = new InventoryDTO();
            PurchaseReturnViewModel.PurchaseReturn.PurchaseReturnDetails.Add(PurchaseReturnDetail);
        }

        public void DeletePurchaseReturnDetail(Object param)
        {
            var PurchaseReturnDetail = (PurchaseReturnDetailDTO) param;
            if (PurchaseReturnViewModel.PurchaseReturn.PurchaseReturnDetails.Count > 1)
            {
                if (param == null)
                {
                    int count = PurchaseReturnViewModel.PurchaseReturn.PurchaseReturnDetails.Count;
                    PurchaseReturnViewModel.PurchaseReturn.PurchaseReturnDetails.RemoveAt(count-1);
                    
                }else
                {
                    PurchaseReturnViewModel.PurchaseReturn.PurchaseReturnDetails.Remove(PurchaseReturnDetail);
                }
                
            }
        }

  

        public bool CanGetInventoryCommand(Object param)
        {
            return true;
        }

        public bool CanGetQtyUnit(Object param)
        {
            return true;
        }

        public void GetQtyUnit(Object param)
        {
            PurchaseReturnDetail = (PurchaseReturnDetailDTO) param;
            if (PurchaseReturnDetail.Inventory != null)
                if (PurchaseReturnDetail.Inventory.SatuanUnit != null)
                {
                    PurchaseReturnDetail.Qty = PurchaseReturnDetail.Inventory.QtyPack *
                                                            (PurchaseReturnDetail.Panjang *
                                                             PurchaseReturnDetail.Lebar *
                                                             PurchaseReturnDetail.Tinggi) /
                                                            PurchaseReturnDetail.Inventory.SatuanUnit.Pengali;
                    PurchaseReturnDetail.Qty = PurchaseReturnDetail.Inventory.Item.IsRounded
                                            ? System.Math.Round(PurchaseReturnDetail.Qty, 2)
                                            : Math.Round(PurchaseReturnDetail.Qty, 4);

                }
                   


        }

  
    }
}